package gw.com.android.model;

import com.gwtsz.gts2.hx.BuildConfig;
import com.gwtsz.gts2.hx.R;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.app.GTConfig;
import gw.com.android.utils.CacheUtils;
import gw.com.android.utils.ChannelUtil;
import gw.com.android.utils.ENV;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.AESCrypto;
import www.com.library.util.DeviceUtil;
import www.com.library.util.DoubleConverter;
import www.com.library.util.JsonUtil;

/**
 * Created by reeta.zou on 2016/7/27.
 * 管理和读取配置文件类
 */
public class ConfigUtil {
    /**
     * 功能配置文件名,简体中文配置文件，繁体中文配置文件
     */
    private String mErrorFileName = "Error_title_zh.json";
    private String mTwErrorFileName = "Error_title_tw.json";
    public String mFileName = ENV.isUat() ? "Func_uat.json" : "Func_prd.json";

    /**
     * 配置文件，简体中文配置文件，繁体中文配置文件对象
     */
    public JSONObject mConfigObject;
    public JSONObject mErrorConfigObject;
    private JSONObject mChooseObject;
    public String urlJsonStr = "";

    private static ConfigUtil mInstance = null;

    public static ConfigUtil instance() {
        if (null == mInstance) {
            mInstance = new ConfigUtil();
        }

        if (null == mInstance.mConfigObject) {
            mInstance.initConfig();
        }
        return mInstance;
    }

    /**
     * 读取本地缓存文件下的配置文件
     */
    private String getFunConfig() {
        String fileContent = CacheUtils.readFile(mFileName + DeviceUtil.instance().appVersionCode(AppMain.getApp())).trim();
        if (null == fileContent || fileContent.length() < 1 || !JsonUtil.isJsonData(fileContent)) {
            Logger.e("fileContent is null");
            fileContent = getFromAssets(mFileName);
        } else {
            try {
                new JSONObject(fileContent);
            } catch (JSONException e) {
                e.printStackTrace();
                Logger.e("fileContent is JSONException");
                fileContent = getFromAssets(mFileName);
            }
        }
        return fileContent;
    }

    /**
     * 读取本地asset文件下的文件
     */
    private String getFromAssets(String fileName) {
        StringBuilder sb = new StringBuilder();
        InputStreamReader inputReader = null;
        BufferedReader bufReader = null;
        try {
            inputReader = new InputStreamReader(AppMain.getApp().getResources().getAssets().open(fileName));
            bufReader = new BufferedReader(inputReader);
            String line;
            while ((line = bufReader.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        } catch (Exception e) {
            try {
                if (null != inputReader) {
                    inputReader.close();
                    inputReader = null;
                }
                if (null != bufReader) {
                    bufReader.close();
                    bufReader = null;
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                if (null != inputReader) {
                    inputReader.close();
                }
                if (null != bufReader) {
                    bufReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
        return sb.toString();
    }


    /**
     * 读取文件到json对象
     */
    private void initConfig() {
        try {
            urlJsonStr = getFunConfig();
            mConfigObject = new JSONObject(urlJsonStr);
            mChooseObject = mConfigObject.optJSONObject(ConfigType.FUNCTION_CHOOSE_TAG);
            if (GTConfig.instance().getLanguage().equals(GTConfig.LANG_ZH_CN)) {
                mErrorConfigObject = new JSONObject(getFromAssets(mErrorFileName));
            } else {
                mErrorConfigObject = new JSONObject(getFromAssets(mTwErrorFileName));
            }
            //   replace VerUpcompanyId ... auto pack
            String companyId = mConfigObject.optString("companyId");
            String verparam = "company_id=" + companyId + "&app_id=" + BuildConfig.APP_ID;
            mConfigObject.put("VerUpcompanyId", verparam);
            urlJsonStr = mConfigObject.toString();
            //   "VerUpcompanyId":"company_id=18&app_id=0",
        } catch (JSONException e) {
            mConfigObject = new JSONObject();
            mChooseObject = new JSONObject();
            mErrorConfigObject = new JSONObject();
        }
    }

    /**
     * 返回错误提示文案对象
     */
    public JSONObject getErrorConfigObject() {
        return mErrorConfigObject;
    }

    /**
     * 切换语言
     */
    public void changeLanguage() {
        try {
            if (GTConfig.instance().getLanguage().equals(GTConfig.LANG_ZH_CN)) {
                mErrorConfigObject = new JSONObject(getFromAssets(mErrorFileName));
            } else {
                mErrorConfigObject = new JSONObject(getFromAssets(mTwErrorFileName));
            }

        } catch (JSONException e) {
            e.printStackTrace();
            mErrorConfigObject = new JSONObject();
        }
    }

    /**
     * 返回url地址配置对象
     */
    public JSONObject getHtmlUrlObject() {
        return mConfigObject.optJSONObject(ConfigType.HTML_TAG);
    }

    /**
     * 返回url地址配置对象
     */
    public JSONObject getHttpUrlObject() {
        return mConfigObject.optJSONObject(ConfigType.HTTP_URL_TAG);
    }

    /**
     * 返回http相关地址ip
     */
    public String getHttpUrlIp(String urlKey) {
        String preUrl = "";
        if (null != urlKey && urlKey.length() > 0) {
            JSONObject jsonObject = getHttpUrlObject();
            if (null == jsonObject) {
                return "";
            }
            jsonObject = jsonObject.optJSONObject(urlKey);
            preUrl = jsonObject.optString
                    (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL ? ConfigType.REAL_TAG : ConfigType.DEMO_TAG);
        }

        return preUrl;
    }

    /**
     * 是否有首页功能,首页功能，0标识没有首页(cf,gww)，1标识原生首页(hx)，2标识嵌套首页(fx)
     */
    public int homeFucType() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.HOME_FUNCTION_TAG)) {
            return 1;
        }
        return mChooseObject.optJSONObject(ConfigType.HOME_FUNCTION_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 是否有分享功能
     */
    public boolean hasShareFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.SHARE_FUNC_TAG)) {
            return true;
        }
        return mChooseObject.optJSONObject(ConfigType.SHARE_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG) == 1;
    }

    /**
     * 是否有平仓分享功能
     */
    public boolean hasOrderShareFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.ORDER_SHARE_FUNC_TAG)) {
            return true;
        }
        return mChooseObject.optJSONObject(ConfigType.ORDER_SHARE_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG) == 1;
    }

    /**
     * 行情界面样式功能，1标识有热门，搜索功能（fx），2标识无热门，搜索功能（hx）
     */
    public int hasQuoteTypeFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.QUOTE_TYPE_FUNC_TAG)) {
            return 1;
        }
        return mChooseObject.optJSONObject(ConfigType.QUOTE_TYPE_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 客服功能，0标识没有(gww)，1标识没有有嵌套客服帮助功能(hx，cf)，2标识有嵌套客服帮助功能(fx)
     */
    public int customerFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.CUSTOMER_FUNC_TAG)) {
            return 0;
        }
        return mChooseObject.optJSONObject(ConfigType.CUSTOMER_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 是否有新手引导，fx，hx和cf有,gww没有
     */
    public boolean hasUserGuideFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.USER_GUIDE_FUNC_TAG)) {
            return true;
        }
        return mChooseObject.optJSONObject(ConfigType.USER_GUIDE_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG) == 1;
    }

    /**
     * 合约属性界面点差是否为固定，hx为固定，fx和cf不是
     */
    public boolean hasSpreadFixFunction() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.SPREAD_FIX_FUNC_TAG)) {
            return true;
        }
        return mChooseObject.optJSONObject(ConfigType.SPREAD_FIX_FUNC_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG) == 1;
    }

    /**
     * 是否行情界面有分版块功能
     */
    public boolean hasZoneDisplay() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.ZONE_DISPLAY_TAG)) {
            return true;
        }
        return mChooseObject.optJSONObject(ConfigType.ZONE_DISPLAY_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG) == 1;
    }

    /**
     * 首页广告样式
     */
    public int getAdsType() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.HOME_ADS_TYPE_TAG)) {
            return AppContances.HOME_ADS_NO_TITLE_TYPE;
        }
        return mChooseObject.optJSONObject(ConfigType.HOME_ADS_TYPE_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 返回热门界面显示类型样式，0没有，1只有涨幅，2有涨幅和涨跌，3有涨幅，涨跌和速涨榜
     */
    public int getHotQuoteType() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.HOT_QUOTE_TYPE_TAG)) {
            return 3;
        }
        return mChooseObject.optJSONObject(ConfigType.HOT_QUOTE_TYPE_TAG).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 返回定时刷新的时间
     */
    public int getHotQuoteTime() {
        if (null == mChooseObject || null == mChooseObject.optJSONObject(ConfigType.HOT_QUOTE_TASK_TIME)) {
            return AppContances.TIMER_HOTQUOTE_TASK_TIME;
        }
        return mChooseObject.optJSONObject(ConfigType.HOT_QUOTE_TASK_TIME).optInt(ConfigType.CONFIG_TYPE_TITLE_TAG);
    }

    /**
     * 获取根据自定义的特殊字段替换成相应逻辑的连接
     */
    public static String getDealStrUrl(String dirUrl) {
        if (dirUrl == null) {
            return null;
        }
        //替换渠道
        if (dirUrl.contains(ConfigType.REPLACE_CHANNEL_TAG)) {
            ChannelUtil channelUtil = new ChannelUtil();
            dirUrl = dirUrl.replace(ConfigType.REPLACE_CHANNEL_TAG, channelUtil.getChannel(AppMain.getApp()));
        }
        //替换平台
        if (dirUrl.contains(ConfigType.REPLACE_PLATFORM_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_PLATFORM_TAG, "android");
        }
        if (dirUrl.contains(ConfigType.REPLACE_VERSION_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_VERSION_TAG, String.valueOf(BuildConfig.VERSION_CODE));
        }
        //替换语言
        if (dirUrl.contains(ConfigType.REPLACE_LANGUAGE_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_LANGUAGE_TAG, GTConfig.instance().getLanguage());
        }
        //替换登录名
        if (dirUrl.contains(ConfigType.REPLACE_LOGIG_NAME_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_LOGIG_NAME_TAG, GTConfig.instance().mCurName);
        }
        //替换包名
        if (dirUrl.contains(ConfigType.REPLACE_APPID_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_APPID_TAG, BuildConfig.APPLICATION_ID);
        }
        //替换活动token
        if (dirUrl.contains(ConfigType.REPLACE_TOKEN_TAG)) {
            dirUrl = dirUrl.replace(ConfigType.REPLACE_TOKEN_TAG, GTConfig.instance().mOpenApiToken);
        }
        //替换加密登录名
        if (dirUrl.contains(ConfigType.REPLACE_ENCRYP_NAME_TAG)) {
            try {
                String encryptName = AESCrypto.Encrypt(GTConfig.instance().mCurName);
                if (encryptName == null) {
                    encryptName = "";
                }
                dirUrl = dirUrl.replace(ConfigType.REPLACE_ENCRYP_NAME_TAG, encryptName);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return dirUrl;
    }

    /**
     * 返回url连接
     */
    public String getUrlPath(String key) {
        JSONObject jsonObject = getHtmlUrlObject();
        if (null == jsonObject) {
            return "";
        }
        jsonObject = jsonObject.optJSONObject(key);
        String preUrl = "";
        String dirUrl = "";
        String paramUrl = "";
        if (null != jsonObject) {
            String urlKey = jsonObject.optString(ConfigType.HTML_URL_TAG);
            if (null != urlKey && urlKey.length() > 0) {
                JSONObject object = getHttpUrlObject();
                if (null == object) {
                    return "";
                }
                object = object.optJSONObject(urlKey);
                preUrl = object.optString
                        (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL ? ConfigType.REAL_TAG : ConfigType.DEMO_TAG);
            }
            dirUrl = jsonObject.optString(ConfigType.HTML_DIR_TAG);
            dirUrl = getDealStrUrl(dirUrl);
        }

        return AppMain.getAppString(R.string.http_url_format, preUrl, dirUrl, paramUrl);
    }

    /**
     * 返回资讯详情html
     */
    public String getNewsUrl(String key, DataItemDetail itemDetail) {

        JSONObject jsonObject = getHtmlUrlObject();
        if (null == jsonObject) {
            return "";
        }
        jsonObject = jsonObject.optJSONObject(key);
        String preUrl = "";
        String dirUrl = "";
        String paramUrl = "";
        if (null != jsonObject) {
            String urlKey = jsonObject.optString(ConfigType.HTML_URL_TAG);
            if (null != urlKey && urlKey.length() > 0) {
                JSONObject object = getHttpUrlObject();
                if (null == object) {
                    return "";
                }
                object = object.optJSONObject(urlKey);
                preUrl = object.optString
                        (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL ? ConfigType.REAL_TAG : ConfigType.DEMO_TAG);
            }
            dirUrl = jsonObject.optString(ConfigType.HTML_DIR_TAG);
//            paramUrl = "/" + typeID + "/" + dataID + ".html";
            JSONArray params = jsonObject.optJSONArray(ConfigType.HTML_PARAM_TAG);
            if (null != params && params.length() > 0) {
                for (int i = 0; i < params.length(); i++) {
                    String value = itemDetail.getString(params.optString(i));
                    paramUrl += "/" + value;
                    Logger.e("paramUrl = " + paramUrl);
                }
            }

            paramUrl += ".html";
        }

        return AppMain.getAppString(R.string.http_url_format, preUrl, dirUrl, paramUrl);
    }

    /**
     * 返回资讯列表图片url
     */
    public String getNewsImageUrl(String key, String dataID) {

        JSONObject jsonObject = getHtmlUrlObject();
        if (null == jsonObject) {
            return "";
        }
        jsonObject = jsonObject.optJSONObject(key);
        String preUrl = "";
        String dirUrl = "";
        String paramUrl = "";
        if (null != jsonObject) {
            String urlKey = jsonObject.optString(ConfigType.HTML_URL_TAG);
            if (null != urlKey && urlKey.length() > 0) {
                JSONObject object = getHttpUrlObject();
                if (null == object) {
                    return "";
                }
                object = object.optJSONObject(urlKey);
                preUrl = object.optString
                        (GTConfig.instance().getAccountType() == GTConfig.ACC_TYPE_REAL ? ConfigType.REAL_TAG : ConfigType.DEMO_TAG);
            }
            dirUrl = jsonObject.optString(ConfigType.HTML_DIR_TAG);
//            JSONArray params = jsonObject.optJSONArray(ConfigType.HTML_PARAM_TAG);
            paramUrl = "/" + DoubleConverter.toIntData(dataID) % 120 + ".png";
        }

        return AppMain.getAppString(R.string.http_url_format, preUrl, dirUrl, paramUrl);
    }

    public JSONArray getDigitalCurrencyTimeRange() {
        if (null == mChooseObject) {
            return null;
        }
        return mConfigObject.optJSONArray(ConfigType.DIGITAL_CURRENCY_TIME_RANGE);
    }
}

